<?php

/**
 * This is the model class for table "slide_banner".
 *
 * The followings are the available columns in table 'slide_banner':
 * @property integer $id
 * @property string $title
 * @property string $image
 * @property string $link
 * @property string $type
 * @property string $status
 */
class SlideBannerModel extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return SlideBannerModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'slide_banner';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('image, type, status', 'required'),
			array('type', 'length', 'max'=>30),
			array('status', 'length', 'max'=>10),
			array('title, link', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, title, image, link, type, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Title',
			'image' => 'Image',
			'link' => 'Link',
			'type' => 'Type',
			'status' => 'Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('link',$this->link,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('status',$this->status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}public function scopes()
{
    return array(
        'sort_id_desc'=>array(
            'order'=>'id DESC',
        ),
        'sort_release_time_desc'=>array(
            'order'=>'release_time DESC',
        ),
        'sort_release_time_asc'=>array(
            'order'=>'release_time ASC',
        ),
    );
}

    public function getByCondition($condition_array,$sort_type ='asc'){
        if($sort_type == 'desc' || $sort_type =='DESC'){
            $data = $this->sort_id_desc()->findAllByAttributes($condition_array);
        }
        else {$data = $this->findAllByAttributes($condition_array);}

        if(sizeof($data) == 0) throw new CHttpException(404,'The requested page does not exist.');
        else{
            $result = array();
            foreach($data as $value){
                $result[] = $value->attributes;
            }
        }
        return $result;
    }

    public function getByID($id){
        $data = $this->findByPk($id);
        if(!is_object($data)){
            return null;
        }else{
            return $data->attributes;
        }

    }


    public function getByIDs($id_array){
        if(sizeof($id_array) == 0 || $id_array==null){
            return null;
        }
        else{
            $data = array();
            foreach($id_array as $value){
                $temp = $this->findByPk($value);
                if(is_object($temp))$data[] = $temp->attributes;
            }
            return $data;
        }
    }

    public function getColumnsByCondition($col_array, $condition_array){
        if($col_array == null || sizeof($col_array) == 0){
            return $this->getByCondition($condition_array);
        }
        else{
            $result = array();
            foreach ($col_array as $value){
                $data = $this->getByCondition($condition_array);
                foreach($data as $val){
                    $result[$value][$val['id']] = $val[$value];
                }
            }
            return $result;
        }
    }

    public function getAll($sort_type ='asc'){
        if($sort_type =='desc'|| $sort_type == 'DESC'){
            $data = $this->sort_id_desc()->findAll();
        }else{ $data = $this->findAll();}

        if(sizeof($data) == 0) throw new CHttpException(404,'The requested page does not exist.');
        else{
            $result = array();
            foreach($data as $value){
                $result[] = $value->attributes;
            }
        }
        return $result;
    }

    public function removeMulti($id_array){
        if(sizeof($id_array) == 0 || $id_array == null){
            return 0;
        }
        else{
            $num_row_deleted = 0;
            foreach($id_array as $value){
                $data = $this->deleteByPk($value);
                $num_row_deleted = $num_row_deleted + $data;
            }
            return $num_row_deleted;
        }
    }

    public function modify($id,$attributes){
        if(sizeof($attributes) == 0 || $attributes == null){
            return null;
        }
        else{
            $data = $this->findByPk($id);
            if(is_object($data)){
                foreach($attributes as $key=>$value){
                    $data->setAttribute($key,$value);
                }
                $result = $data->save(false);
                return $result;
            }
            else return null;
        }
    }

    public function SearchMultiField($string, $conditions, $page_number, $row_limit, $fields){

        $search_array = explode(' ', $string);
        $criteria=new CDbCriteria;

        if($fields == 'all'){
            $fields = array();
            $properties = $this->attributeLabels();
            foreach($properties as $key => $property){
                $fields[] = $key;
            }
        }
        $criteria->condition = '';
        foreach($conditions as $key=> $condition){
            //$criteria->addSearchCondition($key,$condition,true,'AND');
            $criteria->condition .= " $key='$condition' AND ";
        }
        $criteria->condition .= '(';

        foreach($fields as $field){
            foreach($search_array as $search_value){
                if($search_value != '' && $search_value != null){
                    //$criteria->addSearchCondition($field, "%$search_value%", false,'OR');
                    $criteria->condition .= " $field like '%$search_value%'  or ";
                }
            }
        }
        $criteria->condition = substr($criteria->condition, 0, -4);
        $criteria->condition .= ')';
        $criteria->limit = $row_limit;
        $criteria->offset = $row_limit*$page_number-$row_limit;
        $result = array();
        $data = $this->findAll($criteria);
        if(is_array($data)){
            foreach($data as $value){
                $result[] = $value->attributes;
            }
            return $result;
        }else return null;
    }


    public function countSearch($string,$conditions, $fields){

        $search_array = explode(' ', $string);
        $criteria=new CDbCriteria;

        if($fields == 'all'){
            $fields = array();
            $properties = $this->attributeLabels();
            foreach($properties as $key => $property){
                $fields[] = $key;
            }
        }

        foreach($conditions as $key=> $condition){
            //$criteria->addSearchCondition($key,$condition, false,'AND');
            $criteria->condition .= " $key='$condition' AND ";
        }
        $criteria->condition .= '(';
        foreach($fields as $field){
            foreach($search_array as $search_value){
                if($search_value != '' && $search_value != null){
                    //$criteria->addSearchCondition($field, "%$search_value%", false,'OR');
                    $criteria->condition .= " $field like '%$search_value%'  or ";
                }
            }
        }
        $criteria->condition = substr($criteria->condition, 0, -4);
        $criteria->condition .= ')';
        return $this->count($criteria);
    }

    public function validateFilterVal($filter_value){
        $str_len= strlen ($filter_value);
        if($str_len ==0 || $str_len==null){return false;}
        else{
            for($i=0;$i< $str_len; $i++){
                if($i == 0 ){
                    if($filter_value{$i} == '<' || $filter_value{$i} == '>' || $filter_value{$i} == '=')return true;
                    //else return false;
                }else{
                    if($filter_value{$i} == '<' || $filter_value{$i} == '>' || $filter_value{$i} == '=' && $filter_value{$i-1} ==' ')return true;
                    //else return false;
                }
            }
        }
    }

    public function getByPage( $conditions, $page_number, $row_limit, $sort){
        $criteria=new CDbCriteria;
        $criteria->condition = '';
        if($conditions == null || count($conditions) == 0){
            if(is_array($sort)){
                $criteria->order = "";
                foreach ($sort as $sort_field => $sort_type){
                    $criteria->order .= "$sort_field $sort_type , ";
                }
                $criteria->order = substr($criteria->order, 0, -2);
            }
            $criteria->limit = $row_limit;
            $criteria->offset = $row_limit*$page_number-$row_limit;
            $result = array();
            $data = $this->findAll($criteria);
            if(is_array($data)){
                foreach($data as $value){
                    $result[] = $value->attributes;
                }
                return $result;
            }else return null;
        }
        else{
            foreach($conditions  as $property => $condition ){
                if(is_array($condition)){
                    $criteria->condition .= 'AND';
                    $criteria->condition .= '(';
                    foreach($condition as $filter_type => $filter_value){
                        foreach($filter_value as $key => $value){
                            if($this->validateFilterVal($value) == true){
                                if($key == 0)$criteria->condition .= " $property $value ";
                                else $criteria->condition .= " $filter_type $property $value ";
                            }
                            else{
                                if($key == 0)$criteria->condition .= " $property='$value' ";
                                else $criteria->condition .= " $filter_type $property=$value ";
                            }
                        }
                    }
                    $criteria->condition .= ') ';
                }
                else{
                    if($this->validateFilterVal($condition) == true){
                        $criteria->condition .= "AND $property $condition ";
                    }
                    else{
                        $criteria->condition .= "AND $property='$condition' ";
                    }
                }
            }
            $criteria->condition = substr($criteria->condition, 3, -1);
            if(is_array($sort)){
                $criteria->order = "";
                foreach ($sort as $sort_field => $sort_type){
                    $criteria->order .= "$sort_field $sort_type , ";
                }
                $criteria->order = substr($criteria->order, 0, -2);
            }

            $criteria->limit = $row_limit;
            $criteria->offset = $row_limit*$page_number-$row_limit;
            $result = array();
            $data = $this->findAll($criteria);
            if(is_array($data)){
                foreach($data as $value){
                    $result[] = $value->attributes;
                }
                return $result;
            }else return null;
        }
    }

    public function countPage($total_row, $limit){
        if($total_row == 0 || $total_row == null)
            return 0;
        else{
            if($total_row % $limit == 0 )return intval($total_row/$limit);
            else return intval($total_row/$limit)+1;
        }
    }

    public function countRow( $conditions){
        $criteria=new CDbCriteria;
        $criteria->condition = '';
        if($conditions == null || count($conditions) == 0){
            return $this->count($criteria);
        }
        else{
            foreach($conditions  as $property => $condition ){
                if(is_array($condition)){
                    $criteria->condition .= 'AND';
                    $criteria->condition .= '(';
                    foreach($condition as $filter_type => $filter_value){
                        foreach($filter_value as $key => $value){
                            if($this->validateFilterVal($value) == true){
                                if($key == 0)$criteria->condition .= " $property $value ";
                                else $criteria->condition .= " $filter_type $property $value ";
                            }
                            else{
                                if($key == 0)$criteria->condition .= " $property='$value' ";
                                else $criteria->condition .= " $filter_type $property=$value ";
                            }
                        }
                    }
                    $criteria->condition .= ') ';
                }
                else{
                    if($this->validateFilterVal($condition) == true){
                        $criteria->condition .= "AND $property $condition ";
                    }
                    else{
                        $criteria->condition .= "AND $property='$condition' ";
                    }
                }
            }
            $criteria->condition = substr($criteria->condition, 3, -1);

            return $this->count($criteria);

        }
    }

    public function get_start_row($total_row, $page_number, $limit_number){
        if($total_row == 0 || $total_row == null){
            return 0;
        }else{
            $start_row = (($page_number-1)*$limit_number)+1;
            if($start_row > $total_row){
                $start_row = $total_row;
            }
            return $start_row;
        }
    }

    public function get_end_row($total_row, $page_number, $limit_number){
        if($total_row == 0 || $total_row == null){
            return 0;
        }else{
            $end_row = $page_number*$limit_number;
            if($end_row > $total_row){
                $end_row = $total_row;
            }
            return $end_row;
        }
    }

    public function getUnique($field, $sort_type = 'asc'){
        $criteria=new CDbCriteria;
        //$criteria->select = $field;
        $criteria->group = $field;
        $criteria->order = "$field $sort_type";
        $data = $this->findAll($criteria);
        $result = array();
        if(is_array($data)){
            foreach($data as $value){
                $result[] = $value->attributes;
            }
            return $result;
        }else return  null;
    }


}